package com.Dao.Imp;

import com.Dao.BookshelfDao;
import com.Utils.C3P0Utils;
import com.pojo.Bookshelf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
@Service
@Slf4j
public class BookshelfDaoImp implements BookshelfDao {
    @Override
    public int addToBookshelf(Bookshelf bookshelf) throws SQLException {
        int flag=0;
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql1="select bookImage from bookshelf where username=? and bookName=?";
        String sql="insert into bookshelf(username,bookImage,bookAuthor,bookName,addTime,bookId)values(?,?,?,?,?,?)";
        List<Bookshelf>bookshelves=queryRunner.query(sql1,new BeanListHandler<>(Bookshelf.class),bookshelf.getUsername(),bookshelf.getBookName());
        if(!bookshelves.isEmpty()){//存在
            return flag;
        }else{
            queryRunner.update(sql,bookshelf.getUsername(),bookshelf.getBookImage(),bookshelf.getBookAuthor(),
                    bookshelf.getBookName(),bookshelf.getAddTime(),bookshelf.getBookId());
            flag=1;
        }
        return  flag;
    }
    @Override
    public List<Bookshelf> getMyBook(String username) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select bookId,username,bookImage,bookAuthor,bookName,addTime from bookshelf where username=?";
        List<Bookshelf> bookshelves=queryRunner.query(sql,new BeanListHandler<>(Bookshelf.class),username);
        return bookshelves;
    }
}
